﻿using System.Collections.Generic;

namespace SaveTheQueen.Data
{
    public class DoubleLinkedList<T>
    {
        private DoubleLinkedNode<T> header;
        private DoubleLinkedNode<T> tail;
        private int count;

        public DoubleLinkedList(T firstValue)
        {
            header = new DoubleLinkedNode<T>(null, null, default(T)); //não dá pra botar null no valor de T
            tail = new DoubleLinkedNode<T>(null, null, default(T));

            DoubleLinkedNode<T> node = new DoubleLinkedNode<T>(header, tail, firstValue);
            header.Next = node;
            tail.Previous = node;

            count = 1;
        }
        public DoubleLinkedList()
        {
            header = new DoubleLinkedNode<T>(null, null);
            tail = new DoubleLinkedNode<T>(null, null);

            header.Next = tail;
            tail.Previous = header;

            count = 0;
        }

        public int Count
        {
            get { return count; }
        }
        public bool isEmpty
        {
            get { return (count == 0); }
        }


        public DoubleLinkedNode<T> getIndex(int i)
        {
            if (isEmpty)
            {
                return null;
            }
            else
            {
                int j = 0;
                DoubleLinkedNode<T> node = header.Next;
                while (j < i)
                {
                    node = node.Next;
                    j++;
                }
                return node;
            }
        }
        public void addNode(DoubleLinkedNode<T> node)
        {
            DoubleLinkedNode<T> aux = tail.Previous;

            tail.Previous = node;
            node.Next = tail;
            aux.Next = node;
            node.Previous = aux;
            count++;
        }
        public void addValue(T value)
        {
            addNode(new DoubleLinkedNode<T>(null, null, value)); ;
        }
        public DoubleLinkedNode<T> remove(int i)
        {
            if (isEmpty)
            {
                return null;
            }
            DoubleLinkedNode<T> node = getIndex(i);
            if (null == node)
            {
                return null;
            }
            else
            {
                DoubleLinkedNode<T> previous = node.Previous;
                DoubleLinkedNode<T> next = node.Next;
                previous.Next = next;
                next.Previous = previous;
                node.Previous = null;
                node.Next = null;
                count--;
                return node;
            }
        } 
    }
}
